"""
@filename: userapi.py
@project: flask_project
@author: wlf
@time: 2022-09-07
"""
from flask_restful import Resource, Api
from flask import Blueprint, request, session
from model import db
from libs.response import generate_response
from model.user import UserManager
from sqlalchemy import or_

user_bp = Blueprint("userapi", __name__, url_prefix="/v1")
api = Api(user_bp)


class UserView(Resource):
    def get(self, id=None):
        keyword = request.args.get("keyword")
        result_list = []
        if id is not None:
            user_info = UserManager.query.get(id)
            if user_info is not None:
                result_list.append(user_info)
            else:
                return generate_response(status_code=10001, message="user not found")
        else:
            if keyword is not None:
                users_info = UserManager.query.filter(or_(UserManager.username.like('%'+keyword+'%'),
                                                          UserManager.cellphone.like('%'+keyword+'%'),
                                                          UserManager.school.like('%'+keyword+'%'),
                                                          UserManager.admission_date.like('%'+keyword+'%'))).all()
            else:
                users_info = UserManager.query.all()
            result_list += users_info

        return generate_response(message="get user success", data=[user.to_json1() for user in result_list])

    def delete(self, id):
        del_user = UserManager.query.get(id)
        if del_user:
            del_user.delete = 1
            # db.session.delete(del_user)
            db.session.add(del_user)
            db.session.commit()
            return generate_response(message="delete user success")
        else:
            return generate_response(status_code=10001, message="user not found")

    def put(self, id):
        mod_user = UserManager.query.get(id)
        if mod_user:
            # 可以修改什么属性就接收客户端传递的属性过来即可
            username = request.json.get("username")
            school = request.json.get("school")
            admission_date = request.json.get("admission_date")

            # 修改实例对应的属性
            mod_user.username = username
            mod_user.school = school
            mod_user.admission_date = admission_date

            db.session.add(mod_user)
            db.session.commit()

            return generate_response(message="modify user success")
        else:
            return generate_response(status_code=10001, message="user not found")


api.add_resource(UserView, "/user")
api.add_resource(UserView, "/user/<int:id>", endpoint="userviewapi")
